@icon("res://assets/icons/status_manage.png")
class_name StatusManage extends Node

########################## 有限状态机模型
# 状态对应的节点
var _status_nodes : Dictionary
var _status_nums : int = 0

# 当前运行的状态
var current_status:String
var before_status :String 

# 当前运行的状态节点
var current_node:StatusBase

# 打印调试日志
@export var debug_model := false

# 初始化状态，自动搜索子节点并加入进去 
# 搜索子节点的名称只两种，一个是枚举名称，另外是加前缀的枚举名称；例如枚举为Status.Idle, 那么节点名称为StatusIdle或Idle
func _ready():
	load_child()
func load_child():
	var _status_nodes: Dictionary
	var childen = get_children()
	for child in childen:
		var name = child.name
		name = name.replace("Status","")
		
		_status_nodes[name] = child
		add_status_node(name, child)
		_status_nums += 1

func get_nums():
	return _status_nums
	
# 改变状态
func change_status(next_status:String) -> bool:
	if next_status != current_status:
		if debug_model:
			print("[%s] %s=>%s" % [
				Engine.get_physics_frames(),
				current_status,
				next_status
			])
		
		#1. 初始化新状态
		var next_node = _get_status_node(next_status)
		next_node.start()
		
		#2. 结束旧状态
		current_node.stop()
		
		#3. 指向新状态
		current_node = next_node
		
		#4. 状态变更
		before_status = current_status
		current_status = next_status
		return true
	return false

func start_status_node(status_name:String):
	before_status =  status_name
	current_status =  status_name
	current_node = _get_status_node(status_name)
	current_node.start()
	
func add_status_node(name:String, node:StatusBase):
	_status_nodes[name] = node
	node.manager = self

func _get_status_node(local_status:String):
	return _status_nodes.get(local_status)
	
################# 打印当前的状态值
func is_status(status:String) -> bool:
	return status == current_status
	
func run_process(delta: float) -> void:
	current_node.run_process(delta)
	
func run_physics_process(delta: float) -> void:
	current_node.run_physics_process(delta)
